#include <cmath>
#include <iostream>
#include <map>
 
struct Point { double x, y; };
 
// 比较二个 Pointer 指针的 x 坐标
struct PointCmp {
    bool operator()(const Point *lhs, const Point *rhs) const { 
        return lhs->x < rhs->x; 
    }
};
 
int main() {
    // 注意尽管 x 坐标乱序，亦将按照递增的 x 坐标迭代 map
    Point points[3] = { {2, 0}, {1, 0}, {3, 0} };
 
    // mag 是发送结点地址到其在 x-y 平面中长度的 map
    // 尽管键为指向 Point 的指针，我们希望按照点的 x 坐标而非点的地址为 map 赋序。
    // 通过用 PointCmp 类的比较方法进行。
    std::map<Point *, double, PointCmp> mag({
        { points,     2 },
        { points + 1, 1 },
        { points + 2, 3 }
    });
 
    // 从 0 到长度更改每个 y 坐标
    for(auto iter = mag.begin(); iter != mag.end(); ++iter){
        auto cur = iter->first; // 指向 Point 的指针
        cur->y = mag[cur]; // 亦能用 cur->y = iter->second;
    }
 
    // 更新并打印每个点的长度
    for(auto iter = mag.begin(); iter != mag.end(); ++iter){
        auto cur = iter->first;
        mag[cur] = std::hypot(cur->x, cur->y);
        std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is ";
        std::cout << iter->second << '\n';
    }
 
    // 以基于范围的 for 循环重复上述内容
    for(auto i : mag) {
        auto cur = i.first;
        cur->y = i.second;
        mag[cur] = std::hypot(cur->x, cur->y);
        std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is ";
        std::cout << mag[cur] << '\n';
        // 注意与上述 std::cout << iter->second << '\n'; 相反，
        // std::cout << i.second << '\n'; 将不打印更新的长度
    }
}

/*
The magnitude of (1, 1) is 1.41421
The magnitude of (2, 2) is 2.82843
The magnitude of (3, 3) is 4.24264
The magnitude of (1, 1.41421) is 1.73205
The magnitude of (2, 2.82843) is 3.4641
The magnitude of (3, 4.24264) is 5.19615
*/
